// utils/apiErrorHandler.js - API错误处理工具

/**
 * 处理API响应错误
 * @param {Object} response - API响应数据
 * @param {number} response.code - 业务状态码
 * @param {string} response.message - 错误信息
 * @param {Object} options - 处理选项
 * @param {boolean} options.showToast - 是否显示Toast提示
 * @param {boolean} options.showModal - 是否显示Modal提示
 * @param {string} options.defaultMessage - 默认错误信息
 * @returns {Object} 处理结果
 */
const handleApiError = (response, options = {}) => {
  const {
    showToast = true,
    showModal = false,
    defaultMessage = "操作失败，请重试",
  } = options;

  // 提取错误信息
  const errorMessage = response?.message || response?.msg || defaultMessage;
  const errorCode = response?.code;

  console.error("API错误:", {
    code: errorCode,
    message: errorMessage,
    response: response,
  });

  // 显示错误提示
  if (showToast) {
    wx.showToast({
      title: errorMessage,
      icon: "none",
      duration: 2000,
    });
  }

  if (showModal) {
    wx.showModal({
      title: "提示",
      content: errorMessage,
      showCancel: false,
      confirmText: "知道了",
      confirmColor: "#ff6b6b",
    });
  }

  return {
    success: false,
    code: errorCode,
    message: errorMessage,
    data: response?.data || null,
  };
};

/**
 * 检查API响应是否成功
 * @param {Object} response - API响应数据
 * @returns {boolean} 是否成功
 */
const isApiSuccess = (response) => {
  return response && (response.code === 0 || response.code === "0");
};

/**
 * 处理API响应的统一方法
 * @param {Object} response - API响应数据
 * @param {Object} options - 处理选项
 * @returns {Object} 处理结果
 */
const handleApiResponse = (response, options = {}) => {
  if (isApiSuccess(response)) {
    return {
      success: true,
      code: response.code,
      message: response.message || "操作成功",
      data: response.data,
    };
  } else {
    return handleApiError(response, options);
  }
};

/**
 * 创建API请求的错误处理包装器
 * @param {Function} apiCall - API调用函数
 * @param {Object} errorOptions - 错误处理选项
 * @returns {Function} 包装后的函数
 */
const withErrorHandling = (apiCall, errorOptions = {}) => {
  return async (...args) => {
    try {
      const response = await apiCall(...args);
      return handleApiResponse(response, errorOptions);
    } catch (error) {
      console.error("API调用异常:", error);

      // 处理网络异常或其他错误
      const errorMessage = error?.message || "网络异常，请检查网络连接";

      if (errorOptions.showToast !== false) {
        wx.showToast({
          title: errorMessage,
          icon: "none",
          duration: 2000,
        });
      }

      return {
        success: false,
        code: -1,
        message: errorMessage,
        data: null,
        error: error,
      };
    }
  };
};

/**
 * 批量处理API响应的错误
 * @param {Array} responses - API响应数组
 * @param {Object} options - 处理选项
 * @returns {Object} 处理结果
 */
const handleBatchApiResponses = (responses, options = {}) => {
  const results = responses.map((response) =>
    handleApiResponse(response, options)
  );

  const successCount = results.filter((result) => result.success).length;
  const totalCount = results.length;

  if (successCount === totalCount) {
    return {
      success: true,
      message: "所有操作成功",
      data: results.map((result) => result.data),
    };
  } else {
    const failedResults = results.filter((result) => !result.success);
    const errorMessages = failedResults
      .map((result) => result.message)
      .join("；");

    return {
      success: false,
      message: `部分操作失败：${errorMessages}`,
      data: results,
    };
  }
};

module.exports = {
  handleApiError,
  isApiSuccess,
  handleApiResponse,
  withErrorHandling,
  handleBatchApiResponses,
};
